package pe.gob.foncodes.ssa.bs.common.util;

import java.util.ResourceBundle;

public class MessageResources {

    private ResourceBundle bundle;

    public MessageResources(ResourceBundle bundle) {
        setBundle(bundle);
    }

    public ResourceBundle getBundle() {
        return bundle;
    }

    public void setBundle(ResourceBundle bundle) {
        this.bundle = bundle;
    }

    public boolean contains(String key) {
        try {
            bundle.getObject(key);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    public boolean isPresent(String key) {
        return contains(key);
    }

    public String getMessage(String key) {
        try {
            return bundle.getString(key);
        } catch (Exception e) {
            return key;
        }
    }

    public String getMessage(String key, Object... args) {
        try {
            return fillMessageArgs(bundle.getString(key), args);
        } catch (Exception e) {
            return key;
        }
    }

    private String fillMessageArgs(String string, Object... args) {
        for (int i = 0; args != null && i < args.length; i++) {
            string = string.replace("{" + i + "}", String.valueOf(args[i]));
        }
        return string;
    }
}
